package com.yxq.mdt.app.modules.personal.ui.anchor;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.ToastUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.base.BaseActivity;
import com.yxq.mdt.app.glide.GlideHelper;
import com.yxq.mdt.app.modules.personal.bean.RealNameResultBean;
import com.yxq.mdt.app.modules.personal.model.RealNameModel;
import com.yxq.mdt.app.modules.personal.presenter.IRealNameContract;
import com.yxq.mdt.app.modules.personal.presenter.RealNamePresenter;
import com.yxq.mdt.app.net.API;
import com.yxq.mdt.app.modules.webview.ui.MiWebViewActivity;
import com.yxq.mdt.app.utils.GlideEngine;
import com.yxq.mdt.app.widgets.OssHelper;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 提现信息采集
 */
public class PersonalWithdrawAc extends BaseActivity<RealNamePresenter> implements IRealNameContract.View {

    @BindView(R.id.personal_withdraw_tv_web)
    TextView personalWithdrawTvWeb;
    @BindView(R.id.authentication_succeed_name)
    EditText authenticationSucceedName;
    @BindView(R.id.authentication_succeed_number)
    EditText authenticationSucceedNumber;
    @BindView(R.id.personal_withdraw_iv_front)
    ImageView personalWithdrawIvFront;
    @BindView(R.id.personal_withdraw_iv_upload_front)
    ImageView personalWithdrawIvUploadFront;
    @BindView(R.id.personal_withdraw_iv_back)
    ImageView personalWithdrawIvBack;
    @BindView(R.id.personal_withdraw_iv_upload_back)
    ImageView personalWithdrawIvUploadBack;
    @BindView(R.id.personal_withdraw_btn_submit)
    Button personalWithdrawBtnSubmit;
    String imgFront;
    String imgBack;

    @Override
    public int getLayoutId() {
        return R.layout.activity_personal_withdraw;
    }

    @Override
    public void initView() {

    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mPresenter = new RealNamePresenter(this, new RealNameModel());
        showLoadingDialog();
        mPresenter.getCardNoAndName();
    }

    @OnClick({R.id.personal_withdraw_tv_web, R.id.personal_withdraw_iv_upload_front, R.id.personal_withdraw_iv_upload_back, R.id.personal_withdraw_btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.personal_withdraw_tv_web:
                Intent intent = new Intent(mActivity, MiWebViewActivity.class);
                intent.putExtra("url", API.PRIVACY_POLICY);
                intent.putExtra("title", "隐私协议");
                startActivity(intent);
                break;
            case R.id.personal_withdraw_iv_upload_front:
                selectImages(10086);
                break;
            case R.id.personal_withdraw_iv_upload_back:
                selectImages(10000);
                break;
            case R.id.personal_withdraw_btn_submit:
                submit();
                break;
        }
    }

    /**
     * 保存信息
     */
    private void submit() {
        if (authenticationSucceedName.getText().toString().length() == 0) {
            ToastUtils.showShort("请输入身份证姓名");
            return;
        }
        if (authenticationSucceedNumber.getText().toString().length() == 0) {
            ToastUtils.showShort("请输入身份证号码");
            return;
        }
        if (imgFront == null) {
            ToastUtils.showShort("请上传身份证人像面照片");
            return;
        }
        if (imgBack == null) {
            ToastUtils.showShort("请上传身份证国徽面照片");
            return;
        }
        showLoadingDialog();
        mPresenter.saveCard(authenticationSucceedName.getText().toString(), authenticationSucceedNumber.getText().toString(), imgFront, imgBack);
    }

    /**
     * 上传图片至阿里云服务器
     *
     * @param fileName 本地图片文件路径
     * @param type     0 证明 1反面
     */
    @SuppressLint("AutoDispose")
    private void uploadAvatar(String fileName, int type) {
        showLoadingDialog();
        Disposable disposable = Observable
                .create((ObservableOnSubscribe<String>) emitter -> {
                    File file = new File(fileName);
                    OssHelper.getOss(mActivity).putObject(OssHelper.getPutObjectRequest(OssHelper.IMAGE + file.getName(), file.getPath()));
                    String url = OssHelper.getOssPrefixUrl(OssHelper.IMAGE, file.getName());
                    emitter.onNext(url);

                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe((String s) -> {
                    hideLoadingDialog();
                    //上传成功
                    switch (type) {
                        case 0:
                            imgFront = s;
                            break;
                        case 1:
                            imgBack = s;
                            break;
                    }
                }, Throwable -> hideLoadingDialog());
    }

    /**
     * 打开图片选择器
     */
    private void selectImages(int result) {
        //相册
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .maxSelectNum(1)//最大选择数目 最大6张减去现在已经添加的张数
                .compress(true)
                .minSelectNum(1)
                .imageSpanCount(4)
                .selectionMode(PictureConfig.MULTIPLE)
                .forResult(result);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 10086:
                    //正面图片
                    List<LocalMedia> images = PictureSelector.obtainMultipleResult(data);
                    GlideHelper.load(mActivity, images.get(0).getCompressPath(), personalWithdrawIvFront);
                    uploadAvatar(images.get(0).getCompressPath(), 0);
                    break;
                case 10000:
                    //背面图片
                    images = PictureSelector.obtainMultipleResult(data);
                    GlideHelper.load(mActivity, images.get(0).getCompressPath(), personalWithdrawIvBack);
                    uploadAvatar(images.get(0).getCompressPath(), 1);
                    break;
                default:
                    throw new IllegalStateException("Unexpected value: " + requestCode);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onLoadSuccess(String data) {
        hideLoadingDialog();
        ToastUtils.showShort("操作成功");
        finish();
    }

    @Override
    public void onLoadFailed(String msg) {
        hideLoadingDialog();
        ToastUtils.showShort(msg);
    }

    @Override
    public void onLoadRealNameSuccess(RealNameResultBean data) {
        hideLoadingDialog();
        if (data != null) {
            if (!TextUtils.isEmpty(data.getIdentityCardFront())) {
                imgFront = data.getIdentityCardFront();
                GlideHelper.load(mActivity, imgFront, personalWithdrawIvFront);
            }
            if (!TextUtils.isEmpty(data.getIdentityCardBack())) {
                imgBack = data.getIdentityCardBack();
                GlideHelper.load(mActivity, imgBack, personalWithdrawIvBack);
            }
            if (!TextUtils.isEmpty(data.getIdentityCardName())) {
                authenticationSucceedName.setText(data.getIdentityCardName());
            }
            if (!TextUtils.isEmpty(data.getIdentityCardNo())) {
                authenticationSucceedNumber.setText(data.getIdentityCardNo());
            }
        }
    }

    @Override
    public void onLoadRealNameFailed(String msg) {
        hideLoadingDialog();
        ToastUtils.showShort(msg + "");
    }
}
